﻿using System;
using DotNetNuke.Common;
using DotNetNuke.Common.Utilities;
using DotNetNuke.Entities.Modules;
using DotNetNuke.Services.Exceptions;
using DotNetNuke.Services.Localization;
using DNNToolkit.Modules.Glossary.Components;
using System.Web.UI.WebControls;
using System.Collections.Generic;
using DotNetNuke.Common.Lists;

namespace DNNToolkit.Modules.Glossary
{
    /// <summary>
    /// The EditGlossary class is used to manage content.
    /// </summary>
    public partial class EditGlossary : PortalModuleBase
    {
        #region Private Methods

        /// <summary>
        /// Populates the categories.
        /// </summary>
        private void PopulateCategories()
        {
            mCategoryCheckBoxs.Items.Clear();
            GlossaryController gController = new GlossaryController();
            var listInfo = gController.ListGlossaryCategoryDefinition();
            foreach (var item in listInfo)
            {
                mCategoryCheckBoxs.Items.Add(new ListItem(item.CategoryName, item.GlossaryCategoryDefinitionID.ToString()));
            }

        }


        /// <summary>
        /// Gets or sets the glossary ID.
        /// </summary>
        /// <value>The glossary ID.</value>
        private long GlossaryID
        {
            get
            {
                if (ViewState["GlossaryID"] != null)
                    return Convert.ToInt64(ViewState["GlossaryID"]);
                return 0L;
            }
            set
            {
                ViewState["GlossaryID"] = value;
            }
        }

        /// <summary>
        /// Populates the glossary.
        /// </summary>
        /// <param name="objGlossary">The obj glossary.</param>
        private void PopulateGlossary(GlossaryInfo objGlossary)
        {
            if (objGlossary.GlossaryCategories != null)
            {
                foreach (var category in objGlossary.GlossaryCategories)
                {
                    foreach (ListItem item in mCategoryCheckBoxs.Items)
                    {
                        if (item.Value == category.GlossaryCategoryDefinitionID.ToString())
                        {
                            item.Selected = true;
                            break;
                        }
                    }
                }
            }
            mTermTextBox.Text = objGlossary.Term;
            objGlossary.Term = mTermTextBox.Text;
            mDefinitionTextBox.Text = objGlossary.Definition;
        }

        /// <summary>
        /// Validate the data.
        /// </summary>
        /// <returns></returns>
        private bool ValidateData()
        {
            mTermValidator.Visible = false;
            mDefinitionValidator.Visible = false;
            mCategoryValidator.Visible = false;
            if (string.IsNullOrEmpty(mTermTextBox.Text))
            {
                mTermValidator.Visible = true;
                return false;
            }
            if (string.IsNullOrEmpty(mDefinitionTextBox.Text))
            {
                mDefinitionValidator.Visible = true;
                return false;
            }
            bool isValid = false;

            foreach (ListItem item in mCategoryCheckBoxs.Items)
            {
                if (item.Selected)
                {
                    isValid = true;
                    break;
                }
            }
            if (!isValid)
                mCategoryValidator.Visible = true;
            return isValid;
        }

        /// <summary>
        /// Save the glossary.
        /// </summary>
        /// <param name="objGlossary">The obj glossary.</param>
        private void SaveGlossary(GlossaryInfo objGlossary)
        {
            foreach (ListItem item in mCategoryCheckBoxs.Items)
            {
                if (item.Selected)

                    objGlossary.GlossaryCategories.Add(new GlossaryCategory { GlossaryCategoryDefinitionID = long.Parse(item.Value) });
            }
            objGlossary.GlossaryID = GlossaryID;
            objGlossary.ModuleID = this.ModuleId;
            objGlossary.Term = mTermTextBox.Text;
            objGlossary.Definition = mDefinitionTextBox.Text;
            objGlossary.DateTimeStamp = DateTime.Now;
        }

        #endregion

        #region Event Handlers

        /// <summary>
        /// Page_Load runs when the control is loaded.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void Page_Load(System.Object sender, System.EventArgs e)
        {
            try
            {
                if (!Page.IsPostBack)
                {
                    PopulateCategories();
                    if (Request.Params["GlossaryID"] != null)
                    {
                        GlossaryID = Convert.ToInt64(Request.Params["GlossaryID"]);
                        GlossaryController controller = new GlossaryController();
                        var objGlossary = controller.GetGlossary(GlossaryID);
                        PopulateGlossary(objGlossary);
                    }
                }
            }
            catch (Exception exc) //Module failed to load
            {
                Exceptions.ProcessModuleLoadException(this, exc);
            }
        }

        /// <summary>
        /// cmdCancel_Click runs when the cancel button is clicked.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void cmdCancel_Click(System.Object sender, System.EventArgs e)
        {
            try
            {
                this.Response.Redirect(Globals.NavigateURL(this.TabId), true);
            }
            catch (Exception exc) //Module failed to load
            {
                Exceptions.ProcessModuleLoadException(this, exc);
            }
        }


        /// <summary>
        /// cmdUpdate_Click runs when the update button is clicked.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void cmdUpdate_Click(System.Object sender, System.EventArgs e)
        {
            if (!ValidateData())
            {
                return;
            }
            try
            {
                GlossaryController controller = new GlossaryController();
                var objGlossary = new GlossaryInfo();
                if (GlossaryID > 0)
                    objGlossary = controller.GetGlossary(GlossaryID);

                SaveGlossary(objGlossary);

                if (objGlossary.GlossaryID > 0)
                {
                    controller.DeleteGlossaryCategoryByGlossary(objGlossary.GlossaryID);
                    controller.UpdateGlossary(objGlossary);
                }
                else
                    controller.CreateGlossary(objGlossary);

                this.Response.Redirect(Globals.NavigateURL());
            }
            catch (Exception exc) //Module failed to load
            {
                Exceptions.ProcessModuleLoadException(this, exc);
            }
        }

        protected void cmdDelete_Click(System.Object sender, System.EventArgs e)
        {
            try
            {
                GlossaryController controller = new GlossaryController();
                var objGlossary = controller.GetGlossary(GlossaryID);
                controller.DeleteGlossary(objGlossary);
                this.Response.Redirect(Globals.NavigateURL(this.TabId), true);
            }
            catch (Exception exc) //Module failed to load
            {
                Exceptions.ProcessModuleLoadException(this, exc);
            }
        }

        #endregion
    }
}